package cn.itrip.mapper;

import cn.itrip.common.Constants;
import cn.itrip.common.Page;
import cn.itrip.common.PropertiesUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @ClassName BaseQuery
 * @Description TODO
 * @Author yaozhaobao
 * @Date 2020/12/23 9:50
 * @Version 1.0
 **/
@Component("baseQuery")
public class BaseQuery<T> {

    private String url = PropertiesUtils.get("database.properties","baseUrl");

    private HttpSolrClient httpSolrClient;

    public BaseQuery(){
        httpSolrClient = new HttpSolrClient(url);
        httpSolrClient.setConnectionTimeout(1000);
        httpSolrClient.setParser(new XMLResponseParser());
    }

    public Page<T> getHotelByPage(SolrQuery query,Integer pageNo,Integer pageSize,Class<T> clazz){
        if(pageNo==null) pageNo= Constants.DEFAULT_PAGE_NO;
        if(pageSize==null) pageSize=Constants.DEFAULT_PAGE_SIZE;
        //设置分页
        query.setStart((pageNo-1)*pageSize);
        query.setRows(pageSize);
        Page page=null;
        //执行查询
        try {
            QueryResponse response=httpSolrClient.query(query);
            SolrDocumentList results= response.getResults();
            page=new Page(pageNo,pageSize, (int) results.getNumFound());
            //数据
            page.setRows(response.getBeans(clazz));

        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return page;
    };







}
